<?php
class UploadModel {
	public function upload($file)
	{
		//最大上传文件大小
		$MAX_SIZE = 20000000;
		//设置Mine类型
		$FILE_MIMES = array
		('image/jpeg','image/jpg','image/gif','image/png','application/msword');
		//设置允许上传的文件类型，按照格式添加
		$FILE_POSTFIX = array
		('.txt');
		//是否允许删除以上传的文件，允许:yes; 不允许:no;
		$DELETE_ENABLE = 'yes';
		
		/**
		*********************************************
		变量设定
		*********************************************
		**/
		$site_name = $_SERVER['HTTP_HOST'];
		$site_url = "http://".$site_name.dirname($_SERVER['PHP_SELF']);
		$site_this = "http://".$site_name.$_SERVER['PHP_SELF'];
		//可见性，为0时只有会员可见，为1时所有人员都可见
		$visibility = true;
		if($visibility)
		{
		 $upload_dir = "upload/public/";
		}else
		{
		 $upload_dir = "upload/private/";
		}
		$upload_url = $site_url."/".$upload_dir;
		
		/**
		*********************************************
		创建上传目录
		*********************************************
		**/
		if(!is_dir($upload_dir))
		{
		 if(!mkdir($upload_dir))
		  die('文件没有创建成功！！');
		 if (!chmod($upload_dir,0777))
		  die("改变权限失败.");
		}
		/**
		*********************************************
		上传文件处理
		*********************************************
		**/
		if($file)
		{
		 //$resourse = fopen('log.txt','a');
		 //fwrite($resourse,date('Y-m-d H:i:s')."上传 - 上传操作的ip地址为: $_SERVER[REMOTE_ADDR]".$_FILES['userfile']['name']." ".$_FILES['userfile']['type']."\n");
		 //fclose($resourse);
		 $file_name = $file['name'];//上传文件的名称
		 $file_type = $file['type'];//上传文件的类型
		 $file_postfix = substr($file_name,strrpos($file_name,"."));//上传文件的后缀
		 
		 //文件大小检查
		 if($file['size'] > $MAX_SIZE)
		 {
		 	return 0;
		  
		 }elseif(!in_array($file_type,$FILE_MIMES) && !in_array($file_postfix,$FILE_POSTFIX))
		 {
		  //return "对不起你所上传的文件类型不符合规定，不允许上传！！";\
		  return 0;
		 }else
		 {
		  return UploadModel::do_upload($upload_dir,$upload_url,$file);
		 }
		}
	}
	
	public function do_upload($upload_dir,$upload_url,$file)
	{
	 
	 
	 $temp_name = $file['tmp_name'];
	 $file_name = $file['name'];
	 //$file_name = str_replace("\\","",$file_name);
	 //$file_name = str_replace("'","",$file_name);
	 $file_postfix = substr($file_name,strrpos($file_name,"."));//上传文件的后缀
	 $timestamp=time();
	 $file_name = $timestamp.$file_postfix;
	 $file_path = $upload_dir.$file_name;
	// mkdir($upload_dir.$timestamp.'/');
	 //chmod($upload_dir.$timestamp.'/',0777);
	 //文件名检查
	 if($file_name = '')
	 {
	  return 0;
	 }
	 $result = move_uploaded_file($temp_name,$file_path);
	 if($result)
		{
		//echo "上传成功！！";
		//echo "<meta http-equiv=\"refresh\"	content=\"1;url=upload.php\">";
		//exit;
		return $file_path;
		}else
		{
		//echo "上传失败！！";
		//echo "<meta http-equiv=\"refresh\" content=\"1;url=upload.php\">";
		//exit;
		return 0;
		}
		//echo "end";
	}
}
?>